package experiment5.task;

import java.io.DataInputStream;
import java.io.IOException;
import java.net.Socket;

/**
 * @Description:
 * @author:fyl
 * @date 2021/4/22 10:01
 * @Modified By:
 * @Modified Date:
 */
public class ClientReceive implements Runnable {
    //用于接受数据的输入流对象
    private DataInputStream inputStream;
    //是否连接
    private boolean connection;

    /**
     * 根据Socket获取输入流对象
     *
     * @param socket 客户端连接的服务器对应的Socket对象
     */
    public ClientReceive(Socket socket) {
        try {
            inputStream = new DataInputStream(socket.getInputStream());
            connection = true;
        } catch (IOException e) {
            e.printStackTrace();
            connection = false;
            CloseUtil.closeAll(inputStream);
        }
    }

    /**
     * 接收数据并显示
     */
    public void receive() {
        String msg = null;
        try {
            msg = inputStream.readUTF();
        } catch (IOException e) {
            e.printStackTrace();
            connection = false;
            CloseUtil.closeAll(inputStream);
        }
        System.out.println(msg);
    }

    /**
     * 只要是连接状态就会一直接受消息
     */
    @Override
    public void run() {
        while (connection) {
            receive();
        }
    }
}
